package com.qtong.service;

import com.qtong.entity.orders.Order;
import com.qtong.entity.screenings.Screening;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class TicketService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 简单的座位锁定 + 订单创建示例（非强一致、仅用于教学/演示）
     * @return orderId or null if failed
     */
    public String lockSeatsAndCreateOrder(String screeningId, java.util.List<com.qtong.dto.SeatDTO> seats, String userId) {
        List<String> acquired = new ArrayList<>();
        try {
            for (com.qtong.dto.SeatDTO s : seats) {
                String key = String.format("lock:screening:%s:%d:%d", screeningId, s.getRow(), s.getCol());
                Boolean ok = redisTemplate.opsForValue().setIfAbsent(key, userId);
                if (ok == null || !ok) {
                    // failed to lock
                    releaseLocks(acquired);
                    return null;
                }
                // set short ttl
                redisTemplate.expire(key, Duration.ofMinutes(5));
                acquired.add(key);
            }

            // push into screening.lockedSeats
            Query q = new Query(Criteria.where("screeningId").is(screeningId));
            Update u = new Update();
            for (com.qtong.dto.SeatDTO s : seats) {
                org.bson.Document doc = new org.bson.Document();
                doc.put("row", s.getRow()); doc.put("col", s.getCol());
                u.push("lockedSeats", doc);
            }
            mongoTemplate.updateFirst(q, u, Screening.class);

            // create order
            Order order = new Order();
            order.setOrderId(UUID.randomUUID().toString());
            order.setUserId(userId);
            order.setScreeningId(screeningId);
            order.setSeats(seats.stream().map(s -> {
                com.qtong.entity.orders.Seat os = new com.qtong.entity.orders.Seat();
                os.setRow(s.getRow()); os.setCol(s.getCol()); os.setPrice(0.0);
                return os;
            }).toList());
            order.setStatus("LOCKED");
            mongoTemplate.save(order);
            return order.getOrderId();
        } catch (Exception e) {
            releaseLocks(acquired);
            return null;
        }
    }

    public void releaseLocks(List<String> keys) {
        if (keys == null || keys.isEmpty()) return;
        for (String k : keys) redisTemplate.delete(k);
    }
}
